--[[
获取桶状态脚本 - 返回JSON格式
KEYS[1]: bucket key
ARGV[1]: currentTime

返回: JSON字符串格式的桶状态 或 nil
--]]

local key = KEYS[1]
local now = tonumber(ARGV[1])

-- 检查桶是否存在
local bucketData = redis.call('GET', key)
if not bucketData then
    return nil
end

-- 解析JSON数据
local bucket = cjson.decode(bucketData)
local capacity = bucket.capacity or 0
local tokens = bucket.tokens or 0
local refillRate = bucket.refillRate or 0
local lastRefillTime = bucket.lastRefillTime or now

-- 更新令牌数量（不保存，只返回当前状态）
if now > lastRefillTime then
    local timeDiff = now - lastRefillTime
    local tokensToAdd = math.floor(timeDiff * refillRate)
    tokens = math.min(capacity, tokens + tokensToAdd)
end

-- 返回更新后的桶状态JSON
local currentState = {
    capacity = capacity,
    tokens = tokens,
    refillRate = refillRate,
    lastRefillTime = lastRefillTime,
    currentTime = now
}

return cjson.encode(currentState) 